<?php
	include_once("../MembersOnly/Authentication.php");
	
function writeShoppingCart()
{
	$cart = $_SESSION['cart'];
	if(!$cart)
	{
		return '<div> Your shopping cart is empty.';
	}
	else
	{
		$items = explode(',',$cart);
		return '<div> You have <a href="ShoppingCart.php"> items in your shopping cart';
	}
}

function ViewCart()
{
	$cart = $_SESSION['cart'];
	if ($cart)
	{
		$items = explode(',',$cart);
		$contents = array();
		foreach($items as $item)
		{
			$contents[$item] = (isset($contents[$item])) ? ($contents[$item] + 1) : 1;
			
		}
		
	}
	
}

function addToCart()
{
	if(isset($_GET['ID']) && (int)$_GET['ID'] > 0)
	{
		$productID=(int)$_GET['ID'];
	}
	else 
	{
		header('Location:Products.php');
	}
	$conn = getConnection();
	$sql = "SELECT ID, Quantity FROM EcsProducts WHERE ID=$productID";
	$result = $conn->query($sql);
    //$rs = $result->fetch_assoc();
    $conn->close();
    //return $rs;
    if(dbNumRows($result) !=1)
    {
    	//Product does not exist!
    	header('Location:Products.php');
    }
    else 
    {
    	$row = $result->fetch_assoc();
    	    	
    }
    $sid = session_id();
    $conn = getConnection();
    $sql = "SELECT ProductID FROM EcsOrderDetails WHERE ProductID=$productID AND Session_ID='$sid'";
    $result = $conn->query($sql); 
    
    if(dbNumRows($result) == 0)
    {
    	$sql = "INSERT INTO EcsOrderDetails (ProductID, Quantity, Session_ID, OrderID, Status, Created_at)
    			VALUES ($productID, 1, '$sid', 0, 'Temp', NOW())";
    	$result = $conn->query($sql);
    }
    else 
    {
    	$sql = "UPDATE EcsOrderDetails SET Quantity = Quantity + 1 WHERE Session_ID = '$sid' AND ProductID = $productID";
    	$result = $conn->query($sql);
    	
    }
    
    $conn->close();
    header('Location:Products.php');
    
}

